package com.bysc.commentservice.service.impl;

import com.bysc.commonutils.enums.CommentEnum;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commentservice.entity.vo.CollectVo;
import com.bysc.commentservice.service.GoodCollectApiService;
import com.bysc.commentservice.utils.SendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ThreadPoolExecutor;

import static com.bysc.commonutils.constant.RedisConstant.*;

@Service
@Slf4j
public class GoodCollectApiServiceImpl implements GoodCollectApiService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private SendMessageService sendMessageService;

    /**
     * 根据用户token进行收藏操作
     *
     * @param collectVo 收藏信息封装对象
     * @param request   请求对象，用于获取用户token
     */
    @Override
    public void collectByToken(CollectVo collectVo, HttpServletRequest request) {
        // 从请求中解析出用户ID
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        // 获取收藏对象ID
        String id = collectVo.getId();
        // Redis集合操作
        SetOperations set = redisTemplate.opsForSet();
        // Redis哈希操作
        HashOperations hash = redisTemplate.opsForHash();
        // 初始化hashKey和setKey
        String hashKey = "";
        String setKey = "";
        // 根据类型获取对应的CommentEnum枚举
        CommentEnum commentEnum = CommentEnum.getByValue(collectVo.getType());
        // 根据枚举类型处理不同的收藏操作
        switch (commentEnum) {
            case POST:
                log.info("处理帖子收藏,用户：{}-{}", userId, id);
                hashKey = COMMENT_POST + id;
                setKey = COMMENT_POST_USER_COLLECT + userId;
                break;
            case STUDYMATERIAL:
                log.info("处理学习资料收藏,用户：{}-{}", userId, id);
                hashKey = STUDY_DATA + id;
                setKey = STUDY_DATA_USER_COLLECT + userId;
                break;
        }
        // 执行收藏或取消收藏操作
        doLike(set, hash, userId, id, hashKey, setKey, commentEnum);
    }

    /**
     * 执行收藏或取消收藏操作
     *
     * @param set     Redis Set操作对象
     * @param hash    Redis Hash操作对象
     * @param userId  用户ID
     * @param id      收藏对象ID
     * @param hashKey Redis哈希键
     * @param setKey  Redis集合键
     * @param type    收藏类型
     */
    private void doLike(SetOperations set, HashOperations hash, String userId, String id, String hashKey, String setKey, CommentEnum type) {
        // 判断 set 的 key 为 setKey 是否有 userId
        boolean isLiked = set.isMember(setKey, id);

        if (isLiked) {
            // 执行取消收藏逻辑
            hash.increment(hashKey, _COLLECT, -1); // 收藏数减1
            set.remove(setKey, id); // 删除 id
        } else {
            // 执行收藏逻辑
            hash.increment(hashKey, _COLLECT, 1);// 收藏数加1
            set.add(setKey, id); // 添加 id 到集合中
            //如果收藏为学习资料 则不需要进行通知
            if (type == type.STUDYMATERIAL) {
                return;
            }
            //收藏成功发送消息
            //异步线程发送通知
            threadPoolExecutor.execute(() -> {
                log.info("异步线程发送收藏通知");
                sendMessageService.doNotice(id, userId, type, "1");
            });
        }
    }


}
